package org.dei.perla.rockfall.utils;

public class TimeElapsed {
	private static long[] startTimes;
	private static long[] endTimes;
	private static volatile boolean stopCounting = false;
	
	public static void setCapacity(int numMessages) {
		startTimes = new long[numMessages];
		endTimes = new long[numMessages];
	}
	
	public static void beginCount(int msgId){
		startTimes[msgId] = System.currentTimeMillis();
	}  
	
	public static void stopCount(int msgId) {
		if (!stopCounting) {
			endTimes[msgId] = System.currentTimeMillis();
		}
	}
	
	public static synchronized void printTimes() {
		if (!stopCounting) {
			stopCounting = false;
			int avg = 0;
			int count = 0;
			for (int i = 0; i < startTimes.length; i++) {
				if (endTimes[i] != 0) {
					System.out.println("Msg " + i + ": " + (endTimes[i] - startTimes[i]) + " ms");
					avg += endTimes[i] - startTimes[i];
					count++;
				}
			}
			System.out.println("Average: " + avg / count + " ms, calculated on " + count + " values.");
			System.exit(0);
		}
	}
}
